package com.passion.solr.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.passion.solr.dao.DemoSolrDao;
import com.passion.solr.entity.DemoSolrDocument;
import com.passion.solr.service.DemoSolrService;
import com.passion.solr.util.SolrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 类描述：服务实现类
 *
 * @author ZhuYin
 * @since 2025年01月02日
 */
@Slf4j
@Service
public class DemoSolrServiceImpl extends ServiceImpl<DemoSolrDao, DemoSolrDocument> implements DemoSolrService {

    /**
     * 方法说明：重写save方法，由于该对象是solr的实体类，所以需要重写save方法
     *
     * @param demoSolrDocument 实体对象
     * @return boolean
     * @author ZhuYin
     * @since 2025年01月03日
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(DemoSolrDocument demoSolrDocument) {
        boolean result = super.save(demoSolrDocument);
        if (result) {
            try {
                result = SolrUtil.saveDocument(demoSolrDocument);
            } catch (Exception e) {
                log.error("Solr保存数据异常：", e);
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateById(DemoSolrDocument demoSolrDocument) {
        boolean result = super.updateById(demoSolrDocument);
        if (result) {
            // 这里要把修改之后的对象反查出来，再重新建索引，该索引会覆盖原来的索引
            demoSolrDocument = super.getById(demoSolrDocument.getId());
            try {
                result = SolrUtil.saveDocument(demoSolrDocument);
            } catch (Exception e) {
                log.error("Solr更新数据异常：", e);
                throw new RuntimeException(e);
            }
        }
        return result;
    }


}
